package thread;

/**
 * @User: vitobo
 * @Date: 2024-07-29
 * @Description: 线程安全问题
 *  由于线程的抢占式执行, 导致当前执行到任意一个指令的时候, 线程都可能被调度走, CPU让别的线程来执行
 *
 *  解决办法:
 *
 *
 */

class Counter{
    public int count = 0;

    public void add(){
        count++;
    }
}
public class ThreadDemo13 {


    // 线程调度 充满随机性
    public static void main1(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        // 两个线程分别针对 counter 来调用 5万次 的 add方法
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println("count= " + counter.count);
    }


}
